package com.ubing.boot.notesforjava.test.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.xmlbeans.SchemaAttributeModel;

import java.util.Scanner;

/**
 * @ClassName : ChatClient
 * @Description : ChatClient
 * @Author : Xxxxx
 * @Date: 2023-03-26 13:56
 */
public class ChatClient {
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 8080;
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChatClientHandler());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync(); // (5)
            Channel channel = f.channel();
            System.out.println("============="+channel.remoteAddress()+"=================");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String str = scanner.nextLine();
                channel.writeAndFlush(str);
            }
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
